package com.tyk.bookstore.back.system.manager.excel.config;

import com.tyk.bookstore.back.common.core.excel.ExcelManager;
import com.tyk.bookstore.back.common.core.model.exception.CustomException;
import com.tyk.bookstore.back.common.core.model.result.CommonResultEnum;
import com.tyk.bookstore.back.common.core.util.AssertUtil;
import com.tyk.bookstore.back.system.manager.excel.model.PermissionExcelVo;
import com.tyk.bookstore.back.system.model.entity.PermissionDo;
import com.tyk.bookstore.back.system.model.result.PermissionResultEnum;
import com.tyk.bookstore.back.system.repository.PermissionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author tyk
 * @description BookExcelConfig
 */
@Configuration
@RequiredArgsConstructor
public class SystemExcelConfig {

    private final PermissionRepository permissionRepository;

    @Bean
    public ExcelManager<PermissionExcelVo> permissionExcelManager() {

        return new ExcelManager<>() {

            @Override
            public void checkRow(PermissionExcelVo data) {
                // 名称不重复
                AssertUtil.isFalse(
                        permissionRepository.exist1Eq(
                                PermissionDo::getName, data.getName(), PermissionDo.class
                        ),
                        PermissionResultEnum.PERMISSION_NAME_ALREADY_EXISTS
                );
                // 权限字符串不重复
                AssertUtil.isFalse(
                        permissionRepository.exist1Eq(
                                PermissionDo::getCode, data.getCode(), PermissionDo.class
                        ),
                        PermissionResultEnum.PERMISSION_CODE_ALREADY_EXISTS
                );
            }

            @Override
            public void handleSaveException(MultipartFile file, Exception e) {
                throw new CustomException(CommonResultEnum.FILE_OR_DATA_FORMAT_ERROR);
            }
        };
    }

}
